package com.example.game.console.controller;

import com.example.game.console.domain.GameInfoVO;
import com.example.game.console.domain.GameItemVO;
import com.example.game.console.domain.GameListVO;
import com.example.game.module.entity.Game;
import com.example.game.module.service.CategoryService;
import com.example.game.module.service.GameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/game")
public class ConsoleGameController {

    @Autowired
    private GameService gameService;
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/console/list")
    public GameListVO getConsoleGameInfo(@RequestParam Integer page, @RequestParam(required = false) String gameName) {

        int pageSize = 5;
        Integer total = gameService.getTotalGames();
        List<Game> games = gameService.getAllGames(page,pageSize,gameName);

        List<GameItemVO> gameItems = games.stream()
                .map(game -> {
                    GameItemVO itemVO = new GameItemVO();
                    itemVO.setId(game.getId());
                    itemVO.setImage(game.getCoverImages());
                    itemVO.setGameName(game.getGameName());
                    itemVO.setPlayerNumber(game.getPlayerNumber());
                    return itemVO;
                })
                .collect(Collectors.toList());

        GameListVO gameListVO = new GameListVO();
        gameListVO.setList(gameItems);
        gameListVO.setTotal(total);

        return gameListVO;
    }

    @GetMapping ("/console/info")
    public GameInfoVO getGameInfo(@RequestParam Long gameId) {

        Game game = gameService.getById(gameId);
        if (game == null) {
            return null;
        }
        GameInfoVO gameInfoVO = new GameInfoVO();
        gameInfoVO.setTitle(game.getTitle());
        gameInfoVO.setCreateTime(game.getCreateTime());
        gameInfoVO.setCoverImages(Collections.singletonList(game.getCoverImages()));
        gameInfoVO.setGameName(game.getGameName());
        gameInfoVO.setReleaseDate(game.getReleaseDate());
        gameInfoVO.setPrice(game.getPrice());
        gameInfoVO.setCategoryId(game.getCategoryId());
        gameInfoVO.setGameDescription(game.getGameDescription());
        gameInfoVO.setRating(game.getRating());
        gameInfoVO.setUpdateTime(game.getUpdateTime());

        return gameInfoVO;

    }

    @PostMapping("/add")
    public String addGame(@RequestParam(name = "gameId", required = false) Long gameId,
                          @RequestParam(name = "gameName") String gameName,
                          @RequestParam(name = "playerNumber") Long playerNumber,
                          @RequestParam(name = "title") String title,
                          @RequestParam(name = "coverImages") String coverImages,
                          @RequestParam(name = "releaseDate") String releaseDate,
                          @RequestParam(name = "price") Float price,
                          @RequestParam(name = "categoryId") Long categoryId,
                          @RequestParam(name = "gameDescription") String gameDescription,
                          @RequestParam(name = "rating") Float rating) {

        try {
            Long resultGameId = gameService.edit(gameId, gameName, playerNumber,
                    title, coverImages, releaseDate, price, categoryId, gameDescription, rating);
            return resultGameId.toString();
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    @PostMapping("/update")
    public String updateGame(@RequestParam(name = "gameId") Long gameId,
                             @RequestParam(name = "gameName") String gameName,
                             @RequestParam(name = "playerNumber") Long playerNumber,
                             @RequestParam(name = "title") String title,
                             @RequestParam(name = "coverImages") String coverImages,
                             @RequestParam(name = "releaseDate") String releaseDate,
                             @RequestParam(name = "price") Float price,
                             @RequestParam(name = "categoryId") Long categoryId,
                             @RequestParam(name = "gameDescription") String gameDescription,
                             @RequestParam(name = "rating") Float rating
                             ) {

        try {
            Long resultGameId = gameService.edit(gameId, gameName.trim(), playerNumber,
                title.trim(), coverImages, releaseDate.trim(), price,
                categoryId, gameDescription, rating);
            return resultGameId.toString();
        }catch (Exception e) {
                return e.getMessage();
        }

    }

    @PostMapping("/delete")
    public ResponseEntity<?> deleteGame(@RequestParam(name = "gameId", required = false) Long gameId,
                                        @RequestParam(name = "categoryId", required = false) Long categoryId) {
        // 参数校验：必须且仅提供一个参数
        if (Stream.of(gameId, categoryId).filter(Objects::nonNull).count() != 1) {
            return ResponseEntity.badRequest().body("必须提供且仅提供一个参数：gameId 或 categoryId");
        }

        try {
            if (gameId != null) {
                // 删除游戏
                int isDeleted = gameService.delete(gameId);
                if (isDeleted == 0) {
                    return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未找到对应游戏，删除失败");
                }
                return ResponseEntity.ok("游戏删除成功");
            } else {
                // 删除分类及其关联游戏
                int isCategoryDeleted = categoryService.delete(categoryId);
                if (isCategoryDeleted == 0) {
                    return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未找到对应分类，删除失败");
                }

                // 获取并删除关联游戏
                List<Game> games = gameService.findCategoryId(categoryId);
                if (!games.isEmpty()) {
                    List<Long> gameIds = games.stream()
                            .map(Game::getId)
                            .collect(Collectors.toList());
                     gameService.listDeletedByGameId(gameIds);
                    // 可根据需要检查是否全部删除成功
                }
                return ResponseEntity.ok("分类及其关联游戏删除成功");
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("删除过程中发生错误: " + e.getMessage());
        }
    }
}
